define(function(require, exports, module){
	
	 /**
     * @name Classify
     * @class 封装素材分类方法，提供 init（初始化）, get（获取分组数据）, gethtml（获取分组html）, check（获取是否完成分组） 方法。
     * @requires popmaterial
     */
	
	var tmpl_group = '<li title="{name}"><span class="glyphicon glyphicon-minus" title="删除"></span><span class="gname">{name}</span><span class="glyphicon glyphicon-pencil" title="编辑" style="display:none;"></span><label>权重：<input type="text" name="weight" value="{weight}" class="clfy_weight"></label></li>';
	
	var tmpl_material = '<tr material_id="{id}"><td class="txtc"><span class="glyphicon glyphicon-minus" title="删除"></span></td><td class="txtl">{name}</td><td class="txtl">{tags}</td><td class="txtc">{width}</td><td class="txtc">{height}</td><td class="txtl"><a href="{landingpage}" target="_blank">{landingpage}</a></td><td class="txtc">{status}</td><td class="txtc"><a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a></td></tr>';
	
	var initClassify = function(option){
		var op = $.extend({
			data: null,
			getgroup: 1,
			getsize: 1,
			groups: [],
			callback: null
		},option);
		
		var hasinit = false;
		
		//var $node = (typeof op.container=='string'?$(op.container):op.container);
		//if($node.size()<1)return;
		
		//$node.append(tmp_box);
		//var groupData = {group:[{name:"分组1", weight:12, materials:[{id:3, name:"素材3", tags:["电器","美的"], width:100, height:100, landingpage:'www.baidu.com', status: 1}]}, {name:"分组2", weight:13, materials:[{id:4, name:"素材4", tags:["电器","国美"], width:100, height:100, landingpage:'www.baidu.com', status: 1}, {id:5, name:"素材5", tags:["洁具","TOTO"], width:100, height:100, landingpage:'www.baidu.com', status: 1}]}]}
		
		
		var classifyObj = {groupNames:[],ids:[]}
		
		var initPlugin = function(data){
			hasinit = true;
			groupData = data;
			//初始化分组列表
			$.each(groupData, function(i,n){
				$('.clfy_grouplist').append(tmpl_group.replaceAll('{name}', n.name).replaceAll('{weight}', n.weight)).find('li:last').data('group', n);
				classifyObj.groupNames.pushOnly(n.name);
			});
			
			//新增分组
			var addGroup = function(){
				var name = checkGroupName($('.clfy_newgroup').val()), w=1;
				if($('.clfy_grouplist li').size()<1)w=100;
				$('.clfy_grouplist').append(tmpl_group.replaceAll('{name}', name).replaceAll('{weight}', w)).find('li:last').data('group', {name:name,weight:w,materials:[]});
				$('.clfy_weight:last').change();
				classifyObj.groupNames.pushOnly(name);
				if($('.clfy_grouplist li.current').size()<1)$('.clfy_grouplist li:first').click();
			}
			$(document).off('click.classify', '.clfy_addgroup').on('click.classify', '.clfy_addgroup', addGroup);
			$(document).off('keyup.classify', '.clfy_newgroup').on('keyup.classify', '.clfy_newgroup', function(e){
				if(e.keyCode == semi.keyCode.ENTER)addGroup();
			});
			
			//删除分组
			$(document).off('click.classify', '.clfy_grouplist .glyphicon-minus').on('click.classify', '.clfy_grouplist .glyphicon-minus', function(){
				var $group = $(this).parents('li'), name = $group.attr('title'), w = $group.data('group').weight;
				$.each($group.data('group').materials, function(i,n){
					var material_id = n.id;
					changeIcon($('.clfy_ungroup tr[material_id='+material_id+']'));
					classifyObj.ids.remove(material_id);
					$('.clfy_hasgroup tr[material_id='+material_id+']').remove();
					
					if($('.clfy_hasgroup tbody tr').size()<1)$('.clfy_hasgroup tbody').append('<tr class="emptytr"><td class="txtc" colspan="8">没有数据</td></tr>');
					
				});
				$group.remove();
				classifyObj.groupNames.remove(name);
				//回收权重给first
				if($('.clfy_weight:first').size()>0){
					var _firstw = parseInt($('.clfy_weight:first').val());
					$('.clfy_weight:first').val(_firstw+w).parents('li').data('group').weight = _firstw+w;
				}else{
					$('.title_hasgroup b').text('...');
				}
			});
			
			//编辑分组
			$(document).off('click.classify', '.clfy_grouplist .glyphicon-pencil').on('click.classify', '.clfy_grouplist .glyphicon-pencil', function(){
				var $editbtn = $(this), $group = $editbtn.parents('li'), name = $group.attr('title'), w = $group.data('group').weight;
				$('.gname',$group).html('<input class="clfy_newname" type="text" placeholder="请填写分组名称" value="'+name+'">');
				$editbtn.after('<button type="button" class="btn btn-info btn-xs">保存</button><button type="button" class="btn btn-default btn-xs">取消</button>').hide();
				$('.clfy_newname',$group).select();
				$('.btn-default',$group).on('click',function(){
					$editbtn.siblings('.btn').remove();
					$('.gname',$group).html(name);
					$editbtn.show();
				});
				
				var saveNewName = function(){
					var newname = $('.clfy_newname',$group).val();
					if(semi.utils.isEmpty(newname))newname = name;
					$editbtn.siblings('.btn').remove();
					$('.gname',$group).html(newname);
					$editbtn.show();
					
					$group.data('group').name = newname;
					classifyObj.groupNames.remove(name);
					classifyObj.groupNames.pushOnly(newname);
					$group.attr('title',newname);
					if($group.hasClass('current')){
						$('.clfy_hasgroup').attr('group',newname);
						$('.title_hasgroup b').text(newname);
					}
				}
				$('.btn-info',$group).on('click',saveNewName);
				$('.clfy_newname',$group).on('keyup', function(e){
					if(e.keyCode == semi.keyCode.ENTER)saveNewName();
				});
			});
			
			//设置分组权重
			$(document).off('keyup', '.clfy_weight').on('keyup', '.clfy_weight', function(){
				var $this = $(this), thisval = $this.val();
				if(thisval.length>0 && !/^\d+$/.test(thisval)){
					$this.val(thisval.replace(/\D/g,''));
				}
			});
			$(document).off('change', '.clfy_weight').on('change', '.clfy_weight', function(){
				var $this = $(this), thisval = parseInt($this.val()),
					$last = $('.clfy_weight').not($this).last(), lastval = parseInt($last.val());
				
				if($('.clfy_weight').size()<2){
					$this.val(100).parents('li').data('group').weight = 100;
				}else if(thisval==0){
					$this.val(1).parents('li').data('group').weight = 1;
					$last.val(lastval+thisval-1).parents('li').data('group').weight = lastval+thisval-1;
				}else if(thisval>=100-$('.clfy_weight').not($this).size()){
					$this.val(100-$('.clfy_weight').not($this).size()).parents('li').data('group').weight = 100-$('.clfy_weight').not($this).size();
					$('.clfy_weight').not($this).each(function(){
						$(this).val(1).parents('li').data('group').weight = 1;
					});
				}else{
					var weightArr = [], otherval = 0;
					$('.clfy_weight').not($this).each(function(){
						weightArr.push($(this));
						otherval += parseInt($(this).val());
					});
					weightArr.reverse();
					$this.val(thisval).parents('li').data('group').weight = thisval;
					if(otherval+thisval<=100){
						$last.val(100-(otherval-lastval+thisval));
						$last.parents('li').data('group').weight = 100-(otherval-lastval+thisval);
					}else{
						var _w = (thisval+otherval)-100;
						$.each(weightArr, function(i,n){
							var _v = parseInt(n.val());
							if(_w<_v-1){
								n.val(_v-_w).parents('li').data('group').weight = _v-_w;
								return false;
							}else{
								n.val(1).parents('li').data('group').weight = 1;
								_w -= (_v-1);
							}
						});
					}
				}
			});
			
			//选择分组
			$(document).off('click.classify', '.clfy_grouplist li').on('click.classify', '.clfy_grouplist li', function(){
				var $this = $(this);
				if(semi.utils.isEmpty($this.data()))return;
				$this.addClass('current').siblings('.current').removeClass('current');
				$('.clfy_hasgroup').attr('group',$this.attr('title'));
				$('.clfy_hasgroup tbody').empty();
				$('.title_hasgroup b').text($this.attr('title'));
				
				$.each($this.data('group').materials, function(i,n){
					var status = '';
					if(n.status==0){
		        		status = '<span class="label label-default">待审核</span>';
		        	}else if(n.status==1){
		        		status = '<span class="label label-success">通过</span>';
		        	}else{
		        		status = '<span class="label label-danger">拒绝</span>';
		        	}
					$('.clfy_hasgroup tbody').append(tmpl_material.replaceAll('{id}', n.id).replaceAll('{name}', n.name).replaceAll('{tags}', n.tags.join(',')).replaceAll('{width}', n.width).replaceAll('{height}', n.height).replaceAll('{landingpage}', n.landingpage).replaceAll('{status}', status));
					$('.clfy_hasgroup tr:last').hoverClass('mouseover').data('info', n);
					$('.clfy_hasgroup tr:last').addClass('zebra-even');
				});
				if($('.clfy_hasgroup tbody tr').size()<1)$('.clfy_hasgroup tbody').append('<tr class="emptytr"><td class="txtc" colspan="8">没有数据</td></tr>');
			});
			$(document).off('mouseenter.classify', '.clfy_grouplist li').on('mouseenter.classify', '.clfy_grouplist li', function(){
				if($(this).children('.btn').size()<1){
					$(this).children('.glyphicon-pencil').show();
				}
			});
			$(document).off('mouseleave.classify', '.clfy_grouplist li').on('mouseleave.classify', '.clfy_grouplist li', function(){
				$(this).children('.glyphicon-pencil').hide();
			});
			
			//添加素材
			$(document).off('click.classify', '.clfy_material .glyphicon-plus').on('click.classify', '.clfy_material .glyphicon-plus', function(){
				var current = $('.clfy_hasgroup').attr('group');
				if(semi.utils.isEmpty(current) || classifyObj.groupNames.indexOf(current)==-1){
					addGroup();
					$('.clfy_grouplist li').click();
					/*$('.clfy_warning').remove();
					$('.clfy_material .panel-heading').append('<span class="clfy_warning">请先选择一个分组吧！</span>');
					setTimeout(function(){
						$('.clfy_material .panel-heading .clfy_warning').fadeOut(function(){$(this).remove()});
					},1000);
					return;*/
				}
				
				var group = $('.clfy_hasgroup').attr('group');
				var arr = $('.clfy_grouplist [title='+group+']').data('group').materials;
				var addtr = function(_tr){
					changeIcon(_tr);
					_tr.clone().appendTo($('.clfy_hasgroup tbody'));
					$('.clfy_hasgroup tbody tr:last').data('info',_tr.data('info')).hoverClass('mouseover');
					arr.pushOnly(_tr.data('info'));
					classifyObj.ids.pushOnly(_tr.attr('material_id'));
				}
				
				if($('.clfy_hasgroup .emptytr').size()>0)$('.clfy_hasgroup .emptytr').remove();
				if($(this).hasClass('addall')){
					if($(this).parents('.clfy_ungroup:first').size()>0)changeIcon($('#classifyList thead tr'));
					$('.clfy_ungroup tbody .glyphicon-plus').each(function(){
						addtr($(this).parents('tr:first'));
					});
				}else{
					addtr($(this).parents('tr:first'));
					if($('#classifyList tbody tr').size()==$('#classifyList tbody .glyphicon-minus').size())changeIcon($('#classifyList thead tr'));
				}
			});
			
			
			//删除素材
			$(document).off('click.classify', '.clfy_material .glyphicon-minus').on('click.classify', '.clfy_material .glyphicon-minus', function(){
				var group = $('.clfy_hasgroup').attr('group');
				
				var deltr = function(_tr){
					var material_id = _tr.attr('material_id');
					changeIcon($('.clfy_ungroup tr[material_id='+material_id+']'));
					$('.clfy_grouplist li').each(function(){
						$(this).data('group').materials.remove(_tr.data('info'));
					});
					classifyObj.ids.remove(material_id);
					$('.clfy_hasgroup tr[material_id='+material_id+']').remove();
				}
				
				if($(this).hasClass('delall')){
					if($('.clfy_ungroup tbody .glyphicon-minus').size()>0)changeIcon($('#classifyList thead tr'));
					$('.clfy_ungroup tbody .glyphicon-minus').each(function(){
						deltr($(this).parents('tr:first'));
					});
				}else{
					deltr($(this).parents('tr:first'));
					if($('#classifyList tbody tr').size()==$('#classifyList tbody .glyphicon-plus').size())changeIcon($('#classifyList thead tr'));
				}
				if($('.clfy_hasgroup tbody tr').size()<1)$('.clfy_hasgroup tbody').append('<tr class="emptytr"><td class="txtc" colspan="8">没有数据</td></tr>');
			});
			
			// 默认选中第一个分组
			if($('.clfy_grouplist li').size()>0)$('.clfy_grouplist li:first').click();
			
		}
		
		//检测分组名称
		var checkGroupName = function(name){
			var txt = '新分组', index = 1;
			if(semi.utils.isEmpty(name)){
				var _name = txt+index;
				while(classifyObj.groupNames.indexOf(_name)!=-1){
					_name = txt+(++index);
				}
				return _name
			}else{
				if(classifyObj.groupNames.indexOf(name)==-1){
					return name
				}else{
					var _name = name+'_'+index;
					while(classifyObj.groupNames.indexOf(_name)!=-1){
						_name = name+'_'+(++index);
					}
					return _name
				}
			}
		}
		
		//切换按钮
		var changeIcon = function(item){
			if($('.glyphicon:first',item).hasClass('glyphicon-minus')){
				$('.glyphicon:first',item).addClass('glyphicon-plus').removeClass('glyphicon-minus').attr('title','添加');
				if($('.glyphicon:first',item).hasClass('delall'))$('.glyphicon:first',item).addClass('addall').removeClass('delall').attr('title','添加本页');
			}else{
				$('.glyphicon:first',item).addClass('glyphicon-minus').removeClass('glyphicon-plus').attr('title','删除');
				if($('.glyphicon:first',item).hasClass('addall'))$('.glyphicon:first',item).addClass('delall').removeClass('addall').attr('title','删除本页');
			}
		}
		
		
		
		/* 表格 */
    	var bodyTemplate = ['<tr material_id="{id}">',
    	                    	'<td class="txtc"><span class="glyphicon glyphicon-plus" title="添加"></span></td>',
	    	                    '<td class="txtl">{name}</td>',
	    	                    '<td class="txtl">{tags}</td>',
	    	                    '<td class="txtc">{width}</td>',
	    	                    '<td class="txtc">{height}</td>',
	    	                    '<td class="txtl"><a href="{landingpage}" target="_blank">{landingpage}</a></td>',
	    	                    '<td class="txtc">{type}</td>',
	    	                    '<td class="txtc">',
	    	                    	'<a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a>',
	    	                    '</td>',
		                     '</tr>'].join('');
    	
    	var pageTemplate = '<div class="gridTotal">共<b>{totalCount}</b>条记录</div>' +
				        '<input type="button" value="首页" class="page-bt first-page" title="首页">' +
				        '<input type="button" value="上一页" class="page-bt pre-page" title="上一页">' +
				        '第{pageNo}页' +
				        '<input type="button" value="下一页" class="page-bt next-page" title="下一页">' +
				        '<input type="button" value="末页" class="page-bt last-page" title="末页">' +
				        '共{totalPage}页'
   
        var grid = Grid.init({
            holder:'classifyList',
            bodyTemplate:bodyTemplate,
            dataSource:'/trp/strategy/get_material/',
            pageTemplate: pageTemplate,
            sendOnPageSize: true
        });
        
        //数据重置：审核状态   0待审核    1通过    2拒绝
    	/*grid.modifyModel(function(data){
    		if(data.status==0){
        		data.status = '<span class="label label-default">待审核</span>';
        	}else if(data.status==1){
        		data.status = '<span class="label label-success">通过</span>';
        	}else{
        		data.status = '<span class="label label-danger">拒绝</span>';
        	}
    	});*/
    	grid.onrowed(function(tr,data){
    		var info = data[$('#classifyList tbody tr').index(tr)];
    		$(tr).data('info', info);
    	});
    	grid.onfilled(function(data){
    		if(op.getgroup==0){
    			data.group = op.groups;
    		}
    		if(!hasinit){
    			$.each(data.group, function(i,n){
    				$.each(n.materials, function(j, m){
    					classifyObj.ids.pushOnly(m.id);
    				});
    			});
    			initPlugin(data.group);
    			
    			sizeoption = '';
       			$.each(data.sizedata, function(i,n){
       				sizeoption += '<option value="'+n.width+'x'+n.height+'">'+n.width+'x'+n.height+'</option>'
       			});
        		$('.classifybox .pageheader [name=measure]').append(sizeoption).removeAttr('disabled').on('change', filterData).select2();
        		
    		}
    		op.getgroup = 0;
    		op.getsize = 0;
    		$('#classifyList tbody tr').each(function(){
    			var material_id = $(this).attr('material_id');
    			if(classifyObj.ids.indexOf(parseInt(material_id))!=-1){
    				changeIcon($('.clfy_ungroup tr[material_id='+material_id+']'));
	    		}
    		});
    		if(($('#classifyList tbody tr').size()==$('#classifyList tbody .glyphicon-minus').size() && $('#classifyList .addall').size()>0) || $('#classifyList .delall').size()>0)changeIcon($('#classifyList thead tr'));
    		$('.ibtn,.addall,.delall').tooltip();
    	});
    	grid.onerror(function(){
    		$dialog.alert('获取素材数据失败，请稍后重试！','warning');
    	});
    	
        
    	//数据搜索
        var filterData = function(){
        	var txt = $('.classifybox .pageheader .searchbox-ipt').val(),
        		//status = $('.classifybox .pageheader select[name=status]').val(),
        		size = $('.classifybox .pageheader [name=measure]').val(),
        		width = '', height = '';
        	
        	if(size!=-1){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
            grid.send($.extend({
        		search_text: txt,
        		width: width,
	        	height: height,
	        	//status: status,
	        	group: op.getgroup,
	        	sizeTag: op.getsize,
        		pageSize: 10,
        		pageNo: 1
        	},op.data));
        };
        filterData();
        
        //按审核状态搜索
        //$('.classifybox .pageheader select[name=status]').on('change', filterData).select2();
        
        //按名称和标签模糊搜索
        $('.classifybox .pageheader .searchbox-btn').on('click.classify', filterData);
        $('.classifybox .pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        /* 预览-dialog */
        require('./popmaterial').init();
	}
	
	var getData = function(param){
		var dataArr = [];
		$('.clfy_grouplist li').each(function(){
			dataArr.push(semi.utils.clone($(this).data('group')));
		});
		if(typeof param!='undefined'){
			var materials = [];
			$.each(dataArr, function(i,n){
				$.each(n.materials, function(j, m){
					materials.push({group:n.name, weight:n.weight, material_id:m.id});
				});
			});
			return materials;
		}else{
			/*$.each(dataArr, function(i,n){
				var materials = [];
				$.each(n.materials, function(j, m){
					materials.push(m.id);
				});
				n.materials = materials;
			});*/
			return dataArr;
		}
		
	}
	
	var getCheckedItems = function(){
		var dataArr = getData(), html = '';
		var _tmpl = '<tr material_id="{id}" gname="{gname}"><td class="txtc ganme">{gname}</td><td class="txtr gweight">{gweight}</td><td class="txtl name">{name}</td><td class="txtc width">{width}</td><td class="txtc height">{height}</td><td class="txtc">{status}</td><td class="txtc"><a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a><span class="glyphicon glyphicon-minus" title="删除"></td></tr>';
		
		$.each(dataArr, function(i,n){
			var gname = n.name, gweight = n.weight;
			$.each(n.materials, function(k,m){
				var status = '';
				if(m.status==0){
					status = '<span class="label label-default">待审核</span>';
				}else if(m.status==1){
					status = '<span class="label label-success">通过</span>';
				}else{
					status = '<span class="label label-danger">拒绝</span>';
				}
				html += (_tmpl.replaceAll('{gname}',gname).replace('{gweight}',gweight).replaceAll('{id}', m.id).replaceAll('{name}', m.name).replaceAll('{width}', m.width).replaceAll('{height}', m.height).replaceAll('{status}', status))
			});
		});
		return html;
	}
	
	var checkClassify = function(){
		var isok = true;
		$('.clfy_grouplist li').each(function(){
			var $li = $(this);
			if(semi.utils.isEmpty($li.data('group').materials)){//#fa535a
				$li.css({'background':'#fc959a','opacity':'0.6'});
				setTimeout(function(){
					$li.css({'background':'#fafafa','opacity':'1'});
				},500);
				isok = false;
			}
		});
		if(!isok){
			$('.clfy_warning').remove();
			$('.classifybox .panel-title:first').after('<span class="clfy_warning" style="width:140px;right:auto;left:100px;">有为空的分组，请检查！</span>');
			setTimeout(function(){
				$('.classifybox .clfy_warning').fadeOut(function(){$(this).remove()});
			},1000);
		}
		return isok;
	}
	
	return {
		init:initClassify,
		get: getData,
		gethtml: getCheckedItems,
		check: checkClassify
	}
});